package com.longrise.bymodule.page.importcontacts;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.bymodule.R;
import com.longrise.bymodule.constant.ByModuleConstants;
import com.longrise.bymodule.utils.PhoneContactHelper;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/7/7.
 * 导入联系人
 */

public class ImportContactsActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "ImportContactsActivity";
    private Toolbar mToolbar;
    private RecyclerView mRcv;
    private ContactsAdapter mAdapter;
    private ArrayList<ContactsBean> mDataList = new ArrayList<>();
    private ArrayList<ContactsBean> mNotAddList = new ArrayList<>();
    private ArrayList<ContactsBean> mCheckedList = new ArrayList<>();
    private TextView mTvdr;
    private TextView mTvqx;
    private ImageView mIvqx;
    private WaveSideBar mSlideBar;
    private EntityBean[] mZimus;
    private RelativeLayout mRlsecond;
    private RelativeLayout mRlbtm;
    private ImageView mIvback;
    public static final String BY_USERID = "by_userid"; //保易的userid
    private String mUserid;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.by_module_activity_importcontacts;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("保易网");
        mToolbar.setNavigationIcon(R.drawable.umeng_by_ic_close_black);
        setSupportActionBar(mToolbar);
        mSlideBar = (WaveSideBar) findViewById(R.id.icontacts_side_bar);
        mRcv = (RecyclerView) findViewById(R.id.icontacts_rv);
        mTvdr = (TextView) findViewById(R.id.icontacts_daoru_tv);
        mTvqx = (TextView) findViewById(R.id.icontacts_checkall_tv);
        mIvqx = (ImageView) findViewById(R.id.icontacts_checkall_iv);
        mIvback = (ImageView) findViewById(R.id.icontacts_back);
        mRlsecond = (RelativeLayout) findViewById(R.id.icontacts_secondtitle);
        mRlsecond.setVisibility(View.GONE);
        mRlbtm = (RelativeLayout) findViewById(R.id.icontacts_checkall_rl);
        mRlbtm.setVisibility(View.GONE);
        getIntentData();
        initData();
        initEvent();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        mUserid = intent.getStringExtra(BY_USERID);
    }

    private void initEvent() {
        mTvdr.setOnClickListener(this);
        mIvqx.setOnClickListener(this);
        mTvqx.setOnClickListener(this);
        mIvback.setOnClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new ContactsUpdateEvent(ContactsUpdateEvent.UpdateType.close));
                finish();
            }
        });
        mAdapter.setOnItemCheckImageClickListener(new ContactsAdapter.ItemCheckImageClickListener() {
            @Override
            public void onClick(int position) {
                if (mDataList != null) {
                    ContactsBean contactsBean = mDataList.get(position);
                    if (contactsBean.isChecked) {
                        contactsBean.isChecked = false;
                        mCheckedList.remove(contactsBean);
                        checkall(false);
                    } else {
                        contactsBean.isChecked = true;
                        mCheckedList.add(contactsBean);
                        if (mDataList.size() != 0 && mCheckedList.size() == mNotAddList.size()) {
                            checkall(true);
                        }
                    }
                    mAdapter.setData(mDataList);
                }
            }
        });
        mSlideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).letter.equals(index)) {
                        ((LinearLayoutManager) mRcv.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });
    }

    private void initData() {
        mSlideBar.setIndexItems("");
        mAdapter = new ContactsAdapter(mContext);
        mRcv.setLayoutManager(new LinearLayoutManager(this));
        mRcv.setAdapter(mAdapter);
        togetLocalContacts();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DZZWTools.dismissDialog2(); //防止dialog 没有完全销毁
    }

    /**
     * 获取本地地址
     */
    private void togetLocalContacts() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                try {
                    PhoneContactHelper helper = new PhoneContactHelper();
                    //String contact = helper.getContact(mContext);
                    String contact = helper.getContactsFast(mContext);
                    e.onNext(contact);
                } catch (Exception ee) {
                    e.onError(ee);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxmanager.addDisposable(d);
                        DZZWTools.showWaitDialog(mContext);
                    }

                    @Override
                    public void onNext(String value) {
                        PrintLog.d(TAG, "value:" + value);
                        toGetContactsList(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        DZZWTools.dismissDialog(null);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 把本地的联系人传到后台 然后后台返回最终需要显示的联系人列表
     */
    private void toGetContactsList(String localcontacts) {
        EntityBean bean = new EntityBean();
        bean.set("address", localcontacts);
        bean.set("dlruserid", mUserid);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", ByModuleConstants.BY_URL,
                "INSY_BBW_addressList", fbean, new LoadDataManager.OnRequestCallListener() {

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            parseResult(bean);
                            mRlsecond.setVisibility(View.VISIBLE);
                            mRlbtm.setVisibility(View.VISIBLE);
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        DZZWTools.dismissDialog(null);
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }

    /**
     * 解析数据
     */
    private void parseResult(final EntityBean bean) {
        Observable.create(new ObservableOnSubscribe<ResultBeans>() {

            @Override
            public void subscribe(ObservableEmitter<ResultBeans> e) throws Exception {
                try {
                    ArrayList<ContactsBean> contactsBeens = new ArrayList<>();
                    EntityBean resultBean = bean.getBean("result");
                    EntityBean[] zimus = null;
                    if (resultBean != null) {
                        zimus = resultBean.getBeans("zimu");
                        EntityBean[] clientlists = resultBean.getBeans("clientlist");
                        for (EntityBean bean1 : clientlists) {
                            String letter = bean1.getString("letter");
                            EntityBean[] namelists = bean1.getBeans("namelist");
                            for (EntityBean bean2 : namelists) {
                                String firstword = bean2.getString("firstword");
                                String backgorund = bean2.getString("backgorund");
                                String name = bean2.getString("name");
                                String isadd = bean2.getString("isadd");
                                EntityBean[] mobilephones = bean2.getBeans("mobilephone");
                                ArrayList<String> phones = new ArrayList<String>();
                                for (EntityBean bean3 : mobilephones) {
                                    String value = bean3.getString("value");
                                    phones.add(value);
                                }
                                ContactsBean contactsBean = new ContactsBean();
                                contactsBean.firstword = firstword;
                                contactsBean.backgorund = backgorund;
                                contactsBean.name = name;
                                contactsBean.isadd = isadd;
                                contactsBean.letter = letter;
                                contactsBean.phoneNums = phones;
                                contactsBeens.add(contactsBean);
                            }
                        }
                    }
                    ResultBeans beans = new ResultBeans();
                    beans.beansList = contactsBeens;
                    beans.zimus = zimus;
                    e.onNext(beans);
                } catch (Exception e1) {
                    e.onError(e1);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBeans>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxmanager.addDisposable(d);
                    }

                    @Override
                    public void onNext(ResultBeans value) {
                        ArrayList<ContactsBean> beansList = value.beansList;
                        mZimus = value.zimus;
                        mDataList.clear();
                        mDataList.addAll(beansList);
                        toInitNotAddList(beansList);
                        mAdapter.setData(mDataList);
                        toInitSlideBar();
                    }

                    @Override
                    public void onError(Throwable e) {
                        PrintLog.d(TAG, e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private class ResultBeans {
        ArrayList<ContactsBean> beansList;
        EntityBean[] zimus;
    }

    /**
     * 将没有添加的 单独放一个集合
     */
    private void toInitNotAddList(ArrayList<ContactsBean> value) {
        for (int x = 0; x < value.size(); x++) {
            ContactsBean contactsBean = value.get(x);
            if (!"1".equals(contactsBean.isadd)) {
                mNotAddList.add(contactsBean);
            }
        }
    }

    private void toInitSlideBar() {
        ArrayList<String> list = new ArrayList<>();
        if (mZimus == null) {
            return;
        }
        for (EntityBean bean : mZimus) {
            String letter = bean.getString("letter");
            if (!TextUtils.isEmpty(letter)) {
                list.add(letter);
            }
        }
        String[] array = list.toArray(new String[list.size()]);
        mSlideBar.setIndexItems2(array);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.icontacts_daoru_tv) { //导入
            toUpladContacts();
        } else if (id == R.id.icontacts_checkall_iv || id == R.id.icontacts_checkall_tv) { //全选
            toCheckAll();
        } else if (id == R.id.icontacts_back) { //关闭按钮
            finish();
        }
    }


    /**
     * 点击全选
     */
    private void toCheckAll() {
        if (mNotAddList.size() == mCheckedList.size()) { //已经是全选状态 除了没有能添加联系人的状态
            checkall(false);
            if (mNotAddList.size() == 0) {  //没有可以添加的联系人
                DZZWTools.showToast(mContext, "您当前暂无可导入联系人", 0);
            } else {
                mCheckedList.clear();
                for (int x = 0; x < mNotAddList.size(); x++) {
                    ContactsBean contactsBean = mNotAddList.get(x);
                    contactsBean.isChecked = false;
                }
                mAdapter.setData(mDataList);
            }
        } else {
            mCheckedList.clear();
            for (int x = 0; x < mNotAddList.size(); x++) {
                ContactsBean contactsBean = mNotAddList.get(x);
                contactsBean.isChecked = true;
                mCheckedList.add(contactsBean);
            }
            if (mCheckedList.size() == 0) { //已经没有可选的人了
                DZZWTools.showToast(mContext, "您当前暂无可导入联系人", 0);
                checkall(false);
            } else {
                checkall(true);
                mAdapter.setData(mDataList);
            }

        }
    }

    private void checkall(boolean flag) {
        if (flag) {
            mIvqx.setImageResource(R.drawable.by_module_check_on);
            mTvqx.setTextColor(Color.parseColor("#2a4fb4"));
        } else {
            mIvqx.setImageResource(R.drawable.by_module_check_none);
            mTvqx.setTextColor(Color.parseColor("#8f8f8f"));
        }
    }


    /**
     * 上传已经选好的联系人
     */
    private void toUpladContacts() {
        if (mCheckedList.size() == 0) {//未选择联系人
            DZZWTools.showToast(mContext, "您未选择联系人", 0);
            return;
        }
        String address = getAddress();
        EntityBean bean = new EntityBean();
        bean.set("address", address);
        bean.set("dlruserid", mUserid);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService("",ByModuleConstants.BY_URL,
                "INSY_BBW_importAddress", fbean, new LoadDataManager.OnRequestCallListener() {

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            EntityBean resultBean = bean.getBean("result");
                            boolean bool = resultBean.getBoolean("bool");
                            if (bool) {
                                uploadSuccess();
                            } else {
                                String resultdesc = bean.getString("resultdesc");
                                DZZWTools.showToast(mContext, resultdesc, 0);
                            }
                        } catch (Exception e) {
                            DZZWTools.showToast(mContext, "导入联系人失败", 0);
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        DZZWTools.dismissDialog(null);
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        DZZWTools.showToast(mContext, "导入联系人失败", 0);
                    }
                });

    }

    /**
     * 上传成功
     */
    private void uploadSuccess() {
        EventBus.getDefault().post(new ContactsUpdateEvent(ContactsUpdateEvent.UpdateType.update)); //通知课程管理首页刷新
        finish();
    }

    private String getAddress() {
        UploadContactsBean bean = new UploadContactsBean();
        for (int x = 0; x < mCheckedList.size(); x++) {
            ContactsBean contactsBean = mCheckedList.get(x);
            ContactItem item = new ContactItem();
            item.id = contactsBean.id;
            item.backgorund = contactsBean.backgorund;
            item.name = contactsBean.name;
            if (contactsBean.phoneNums != null) {
                for (int y = 0; y < contactsBean.phoneNums.size(); y++) {
                    String phoneNums = contactsBean.phoneNums.get(y);
                    Mobilephone mobilephone = new Mobilephone();
                    mobilephone.key = "mobile";
                    mobilephone.value = phoneNums;
                    item.mobilephone.add(mobilephone);
                }
            }
            bean.contacts.add(item);
        }
        Gson gson = new Gson();
        return gson.toJson(bean);
    }

    private class UploadContactsBean {
        public List<ContactItem> contacts = new ArrayList<>();
    }

    private class ContactItem {
        public String id;
        public List<Mobilephone> mobilephone = new ArrayList<>();
        public String backgorund;
        public String name;
    }

    private class Mobilephone {
        public String key;
        public String value;
    }

}
